package com.xpc.controller.qin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xpc.controller.utils.MD5AddSaltToEncrypt;
import com.xpc.controller.utils.ReadExcelInfo;
import com.xpc.controller.utils.SaltGeneration;
import com.xpc.pojo.qin.AccountUser;
import com.xpc.pojo.qin.ListUserAndAccount;
import com.xpc.pojo.User;
import com.xpc.service.IAccountService;
import com.xpc.service.IAccountUserService;
import com.xpc.service.IUserService;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;

import static com.xpc.constant.RolesConstant.ROLE_ADMIN_STRING;
import static com.xpc.constant.StringConstant.RESET_PASSWORD_FAILED_STRING;

/**
 * @author Qinkuer
 * @version 1.0.0
 * @ClassName AdminController.java
 * @Description 用于完成管理员页面操作,批量导入账号,修改账号信息,重置密码等
 * @createTime 2022年05月13日 11:40:00
 */
@RestController
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private IUserService userService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IAccountUserService accountUserService;

/**
    * @description 重置账号的密码
    * @deprecated
    * @param user* 只需要输入userId
    * @return  com.baomidou.mybatisplus.extension.api.R
    * @author Qinkuer
    * @Date  2022/5/13
    */
    @PutMapping("resetpassword")
    public R resetPassword(@RequestBody User user){
        Subject subject = SecurityUtils.getSubject();
        if(!subject.hasRole(ROLE_ADMIN_STRING))
            return R.failed("该账号没有权限操作");

        user.setSalt(SaltGeneration.getSalt());
        user.setPassword(MD5AddSaltToEncrypt.encodeBySalt("123456",user.getSalt()));
        if(userService.updateById(user))
            return R.ok(user.getUserId());
        return R.failed(RESET_PASSWORD_FAILED_STRING);
    }


    /**
        * @description 上传用户信息文件,并导入数据库  (未测试,因为没有对应web页面)
        * @deprecated
        * @param file* 包含用户信息的Excel文件, 一次只支持上传一个 TODO 存在部分表没有插入对象的学生数据.如student表
        * @return  com.baomidou.mybatisplus.extension.api.R
        * @author Qinkuer
        * @Date  2022/5/14
        */
    @PostMapping("uploadfile")
    public R uploadFile(@RequestParam("file")MultipartFile file){
        Subject subject = SecurityUtils.getSubject();
        if(!subject.hasRole(ROLE_ADMIN_STRING))
            return R.failed("该账号没有权限操作");

        //1. 获取user表中最新一行的user_id值
        //2. 对user表插入数据
        //3. 对account表插入数据

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.select("max(user_id) as user_id");
        long maxUserId=userService.getOne(userQueryWrapper).getUserId();

        try {
            ListUserAndAccount userInfo = ReadExcelInfo.getUserInfo(file,maxUserId);
//            return R.ok(userInfo);
            if(userService.saveOrUpdateBatch(userInfo.getUserList())){
                if(accountService.saveOrUpdateBatch(userInfo.getAccountList()))
                    return R.ok(null);
                else
                    return R.failed("导入account表时,失败!");
            }
            else
                return R.failed("导入user表失败!");
        } catch (IOException | InvalidFormatException |NumberFormatException e) {
           return R.failed(e.getMessage());
        }
    }


    /**
        * @description 请求用户详细信息
        * @deprecated
        * @param page* 页码
        *        size* 每页的数据数
        * @return  com.baomidou.mybatisplus.extension.api.R
        * @author Qinkuer
        * @Date  2022/5/18
        */
    @GetMapping("accountUserInfo/{page}/{size}")
    public R getAccountUserInformationByPage(@PathVariable Integer page,@PathVariable Integer size){
        Subject subject = SecurityUtils.getSubject();
        if(!subject.hasRole(ROLE_ADMIN_STRING))
            return R.failed("该账号没有权限操作");
        Page<AccountUser> accountPage = new Page<AccountUser>(page, size);
        return R.ok(accountUserService.getPage(accountPage));
    }

    /**
        * @description 删除账号(管理员限定)
        * @deprecated
        * @param accountId account表的主键
     *           userId 用户的ID
        * @return
        * @author Qinkuer
        * @Date  2022/5/19
        */
    @DeleteMapping("deleteAccount/{accountId}/{userId}")
    public R deleteAccountByAccountId(@PathVariable String accountId,@PathVariable Long userId){
        Subject subject = SecurityUtils.getSubject();
        if(!subject.hasRole(ROLE_ADMIN_STRING))
            return R.failed("该账号没有权限操作");
        if(accountService.removeById(accountId))
            if(userService.removeById(userId)){
                return R.ok(null);
            }
            else{
                return R.failed("删除异常,不存在userID: "+userId.toString());
            }
        return R.failed("删除失败,不存在AccountID: "+accountId);
    }


    /**
        * @description 进行模糊查询请求.请求头与请求用户详细信息相同,是为了方便前端模糊查询分页查找,和分页查看用户详细信息
        * @deprecated
        * @param page, size,
        *        accountId  模糊查询的账号
        * @return  com.baomidou.mybatisplus.extension.api.R
        * @author Qinkuer
        * @Date  2022/5/19
        */
    @GetMapping("accountUserInfo/{page}/{size}/{accountId}")
    public R searchUserByAccountId(@PathVariable Integer page,@PathVariable Integer size,@PathVariable String accountId){
        Subject subject = SecurityUtils.getSubject();
        if(!subject.hasRole(ROLE_ADMIN_STRING))
            return R.failed("该账号没有权限操作");
        Page<AccountUser> accountPage = new Page<AccountUser>(page, size);
        return R.ok(accountUserService.searchByAccountId(accountPage,accountId));
    }


//    TODO 添加角色, 但是感觉有点问题.其他人也可以添加角色啊.这角色到底是啥.
//    @PostMapping("addRole")
//    public R addRole(@RequestBody )
}
